<?php

/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/11/27/0027
 * Time: 15:28
 */

namespace app\exception;

use think\exception\Handle;
use Exception;
use think\Log;
use think\Request;

class ExceptionHandle extends Handle
{

    //状态码
    private $code = 0;
    //返回信息
    private $msg = '';
    //错误码
    private $errorCode = 0;
    //实现render方法(TP5提供)
    public function render(Exception $e)
    {
        if($e instanceof BaseException){
            $this->code = $e->code;
            $this->msg = $e->msg;
            $this->errorCode = $e->errorCode;
        }else{
            $this->code = 500;
            $this->msg = '服务器错误';
            $this->errorCode = 999;
            $this->recordErrorLog($e);
        }
        $result = ['msg'=>$this->msg,'error_code'=>$this->errorCode,'url'=>Request::instance()->url()];
        return json($result,$this->code);
    }
    /**
     * 错误日志写入
     */
    public function recordErrorLog(Exception $e)
    {
        Log::init([
            'type' => 'File',
            'path' => LOG_PATH,
            'level'=> ['error'],
        ]);
        Log::record($e->getMessage(),'error');
    }
}